package org.wuhong.service.impl;

import com.wuhong.entity.Accounts;
import com.wuhong.entity.Files;
import com.wuhong.result.ResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.wuhong.service.FilesService;
import org.wuhong.mapper.FilesMapper;
//import org.wuhong.service.mapper.SdFilePathMapper;
import org.wuhong.utils.NioUploadUtil;
import org.wuhong.utils.SnowIDUtil;

import java.util.List;
import java.util.UUID;

/**

 * @Description TODO
 * @Author director吴
 * @Date 2022/2/10 11:43
 * @Version 1.0
 **/
@Service
public class FilesServiceImpl implements FilesService {

//    @Autowired
//    SdFilePathMapper sdFilePathMapper;

    @Autowired
    FilesMapper filesMapper;




    /*
        将上传文件保存到服务器，并且将路径存到数据库
     */
    @Transactional
    @Override
    public ResultData<Files> saveFile(MultipartFile file) {


        String path = NioUploadUtil.upload(file);
        Files filePath = new Files();

        filePath.setId(SnowIDUtil.snowflakeId());
        filePath.setAddresPath(path);
        filePath.setUserId(UUID.randomUUID().toString());
        filesMapper.insert(filePath);

        ResultData<Files> resultData = new ResultData();
        resultData.setData(filePath);
        resultData.setSuccess(true);
        resultData.setMsg("上传成功！");
        return resultData;
    }


    @Transactional
    public ResultData<Files> saveFileIo(MultipartFile file, Accounts accounts,String folderId) throws Exception {
        //获得文件url和文件bytes字节
        String uploadpath = NioUploadUtil.upload(file);
        byte[] bytes = file.getBytes();

        Files files = new Files();
        files.setId(SnowIDUtil.snowflakeId());
        files.setAddresPath(uploadpath);
        files.setFileStream(bytes);
        files.setName(file.getOriginalFilename());
        files.setUserId(accounts.getId());
        files.setCatalogueId(folderId);

        filesMapper.insert(files);
        filesMapper.insertFilesAndFolder(folderId,files.getId().toString());

        ResultData<Files> resultData = new ResultData();
        resultData.setSuccess(true);
        resultData.setMsg("上传成功！");

        return resultData;
    }



    @Override
    public ResultData<List<Files>> getFileListByUserId(String userId){
        ResultData resultData = new ResultData();
        resultData.setData( filesMapper.selectFiles(userId));
        resultData.setSuccess(true);
        return resultData;
    }

    @Override
    public ResultData<List> getFilesInfo(String userId) {
        ResultData resultData = new ResultData();
        resultData.setData( filesMapper.getFilesInfo(userId));
        resultData.setSuccess(true);
        return resultData;
    }


}
